package bbs2.servlet;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import bbs2.dao.FileDAO;
import bbs2.service.UserService;

@MultipartConfig
@WebServlet("/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            String s = new String(request.getParameter("targetType").getBytes("8859_1"), "utf-8");
            int targetType = Integer.parseInt(s);
            s = new String(request.getParameter("targetId").getBytes("8859_1"), "utf-8");
            int targetId = Integer.parseInt(s);
            String returnUrl = new String(request.getParameter("returnUrl").getBytes("8859_1"), "utf-8");
            Part filePart = request.getPart("file");
            String fileName = getFileName(filePart);            
            int fileSize = (int)filePart.getSize();
            if (fileSize > 0)
                try {
                    int userId = UserService.getCurrentUser(request.getSession()).getId();
                    FileDAO.insert(targetType, targetId, userId, fileName, fileSize, filePart.getInputStream());
                } catch (Exception e) {
                    throw new ServletException(e);
                }
            response.sendRedirect(returnUrl);
    }

    private String getFileName(Part filePart) {
        for (String content : filePart.getHeader("content-disposition").split(";"))
            if (content.trim().startsWith("filename")) {
                String path = content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
                return new File(path).getName();
            }
        return null;
    }

}
